package algorithm.String;

public class BFViolentMatch {
    public static void main(String[] args) {
      String str1 = "ILoveChina";
      String target = "China";
      BFViolentMatch violentMath = new BFViolentMatch();
      int index = violentMath.ViolentMath(str1,target);
      System.out.println(index);
    }

    /**
     * 字符串暴力匹配子串
     * @param sourceString 原字符串
     * @param model  目标字符串
     * @return  返回子串下标，没有返回-1
     */
    public static int ViolentMath(String sourceString,String model){
        int N = sourceString.length();
        int M = model.length();
        int i,j;
        for (i = 0, j = 0;i < N&&j<M; i ++){
            if (sourceString.charAt(i)==model.charAt(j)){
                //如果匹配就接着下一位比较
                j++;
            }else {
                //如果不匹配i就要回退,j重置
                i=i-j;
                j=0;
            }

        }
        if (j==M) return i-j;
        return -1;
    }
}
